<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getApiUrl, API_ENDPOINTS } from '../config/api'

interface Staff {
  id: number
  name: string
  position: string
  department: string
  phone: string
  status: string
}

const staffList = ref<Staff[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentId = ref<number | null>(null)

const formData = ref({
  name: '',
  position: '',
  department: '',
  phone: '',
  status: '在岗'
})

const rules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  department: [{ required: true, message: '请选择部门', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

const departments = ['护理部', '医疗部', '后勤部', '活动部', '行政部', '餐饮部']

// Fetch staff from API
const fetchStaff = async () => {
  try {
    loading.value = true
    const response = await fetch(getApiUrl(API_ENDPOINTS.staff))
    if (!response.ok) throw new Error('获取数据失败')
    const data = await response.json()
    staffList.value = Array.isArray(data) ? data : []
  } catch (error) {
    ElMessage.error('获取员工列表失败')
    staffList.value = []
  } finally {
    loading.value = false
  }
}

// Add new staff member
const addStaff = async () => {
  try {
    const response = await fetch(getApiUrl(API_ENDPOINTS.staff), {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    if (!response.ok) throw new Error('添加失败')
    
    ElMessage.success('添加员工成功')
    dialogVisible.value = false
    await fetchStaff()
    resetForm()
  } catch (error) {
    ElMessage.error('添加员工失败')
  }
}

// Edit staff member
const editStaff = async () => {
  if (!currentId.value) return
  
  try {
    const response = await fetch(getApiUrl(`${API_ENDPOINTS.staff}/${currentId.value}`), {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(formData.value)
    })

    if (!response.ok) throw new Error('更新失败')
    
    ElMessage.success('更新员工成功')
    dialogVisible.value = false
    await fetchStaff()
    resetForm()
  } catch (error) {
    ElMessage.error('更新员工失败')
  }
}

// Delete staff member
const deleteStaff = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除该员工吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await fetch(getApiUrl(`${API_ENDPOINTS.staff}/${id}`), {
      method: 'DELETE'
    })

    if (!response.ok) throw new Error('删除失败')
    
    ElMessage.success('删除员工成功')
    await fetchStaff()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除员工失败')
    }
  }
}

// Handle edit button click
const handleEdit = (row: Staff) => {
  isEdit.value = true
  currentId.value = row.id
  formData.value = { ...row }
  dialogVisible.value = true
}

// Handle add button click
const handleAdd = () => {
  isEdit.value = false
  currentId.value = null
  resetForm()
  dialogVisible.value = true
}

const handleSubmit = () => {
  if (isEdit.value) {
    editStaff()
  } else {
    addStaff()
  }
}

const resetForm = () => {
  formData.value = {
    name: '',
    position: '',
    department: '',
    phone: '',
    status: '在岗'
  }
}

onMounted(() => {
  fetchStaff()
})
</script>

<template>
  <div class="staff">
    <div class="header">
      <h2>员工管理</h2>
      <el-button type="primary" @click="handleAdd">添加员工</el-button>
    </div>

    <el-table 
      :data="staffList" 
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="position" label="职位" />
      <el-table-column prop="department" label="部门" />
      <el-table-column prop="phone" label="联系电话" />
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === '在岗' ? 'success' : 'info'">
            {{ row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button link type="danger" @click="deleteStaff(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- Add/Edit Staff Dialog -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑员工' : '添加员工'"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="formData.position" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="formData.department" style="width: 100%">
            <el-option 
              v-for="dept in departments" 
              :key="dept" 
              :label="dept" 
              :value="dept"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="formData.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" style="width: 100%">
            <el-option label="在岗" value="在岗" />
            <el-option label="休假" value="休假" />
            <el-option label="离职" value="离职" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.staff {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>